import React, { PureComponent } from 'react';
import { func, string, number, bool } from 'prop-types';
import cx from 'classnames';

import './Input.less';

export default class Input extends PureComponent {
  static propTypes = {
    className: string,
    placeholder: string,
    defaultValue: string,
    type: string.isRequired,
    disabled: bool,
    required: bool,
    maxLength: number,
    minLength: number,
    onChange: func.isRequired,
    onPaste: func,
  };

  static defaultProps = {
    className: null,
    type: 'text',
    disabled: false,
    maxLength: null,
    minLength: null,
    onPaste: null,
    placeholder: '',
    required: false,
    defaultValue: '',
  };

  state = {
    value: this.props.defaultValue,
  };

  handlePaste = ev => {
    const { onPaste } = this.props;

    ev.preventDefault();

    const text = ev.clipboardData.getData('Text');
    const returnedValue = onPaste(text);

    this.handleChange({ target: { value: returnedValue } });
  };

  handleChange = ({ target: { value } }) => {
    const { onChange } = this.props;

    this.setState({ value }, () => {
      onChange(value);
    });
  };

  render() {
    const {
      className,
      type,
      maxLength,
      minLength,
      onPaste,
      placeholder,
      required,
      disabled,
    } = this.props;
    const { value } = this.state;

    return (
      <div className={cx('input', className)}>
        <input
          type={type}
          placeholder={placeholder}
          value={value}
          disabled={disabled}
          maxLength={maxLength}
          minLength={minLength}
          required={required}
          onChange={this.handleChange}
          onPaste={onPaste ? this.handlePaste : () => {}}
        />
      </div>
    );
  }
}
